%%%%%%%%
%%% PREPARATION OF THE DATABASE
%%%%%%%%
[m,p,mss] = readmodel(false);
% filter = false - Kalman filtration OFF

%% Load quarterly data
% Command 'dbdload' loads the data from the 'csv' file (save from Excel as
% .csv in the current directory). All the data are now available in the
% database 'd' 
d = dbload('data.csv');

%% Seasonal adjustment
list = dbnames(d);

for i = 1:length(list)
    if length(list{i})>1
        if strcmp('_u', list{i}(end-1:end))
            d.(list{i}(1:end-2)) = x12(d.(list{i}), Inf, 'mode', 'm');
            d = rmfield(d, list{i});
        end
    end
end

%% Make log of variables
exceptions = {'rn','x_rn','target'};

list = dbnames(d);

for i = 1:length(list)
    if isempty(strmatch(list{i},exceptions,'exact'))
        d.(['l' list{i}]) = 100*log(d.(list{i}));
    end
end

%% Define the real exchange rate
d.lz = d.ls + d.lx_cpi - d.lcpi;

%% Food and oil indexes in local currency
d.lfood = d.lwfood + (d.ls - d.ls_cross);
d.loil = d.lwoil + (d.ls - d.ls_cross);

%% Growth rate qoq, yoy
exceptions = {'rn','x_rn','target'};

list = dbnames(d);

for i = 1:length(list)
    if isempty(strmatch(list{i}, exceptions,'exact'))
        if length(list{i})>1
            if strcmp('l', list{i}(1:1))
                d.(['dot_' list{i}(2:end)])  = 4*(d.(list{i}) - d.(list{i}){-1});
                d.(['dot4_' list{i}(2:end)]) = d.(list{i}) - d.(list{i}){-4};
            end
        end
    end
end

%% CPI weights
W_food = 0.27249;
W_oil = 0.03117;
W_x = 1 - W_food - W_oil;

%% Time varying CPI weights
d.W_food = tseries(get(d.cpi,'first2last'),W_food);
d.W_oil = tseries(get(d.cpi,'first2last'),W_oil);
d.W_x = tseries(get(d.cpi,'first2last'),W_x);

d.lw_food    = d.W_food*d.cpi_food{-1}/d.cpi{-1};
d.lw_oil    = d.W_oil*d.cpi_oil{-1}/d.cpi{-1};
d.lw_x    = d.W_x*d.cpi_x{-1}/d.cpi{-1};

d.lw_food    = d.lw_food(end);
d.lw_oil  = d.lw_oil(end);
d.lw_x  = d.lw_x(end);

disp('Time-varying food and oil weights at the end of the sample:');
disp(['lw_food:' num2str(d.lw_food)]);
disp(['lw_oil:' num2str(d.lw_oil)]);

%% Real variables
% Domestic real interest rate
d.rr = d.rn - d.dot4_cpi;

% Fooreign real interest rate
d.x_rr = d.x_rn - d.dot4_x_cpi;

%% Relative food price
d.lz_food = d.lfood - d.lcpi_food;

%% Trends and Gaps - Hodrick-Prescott filter
list = {'rr','lz','x_rr','lz_food'};

for i = 1:length(list)
    [d.([list{i} '_eq']), d.([list{i} '_gap'])] = hpf(d.(list{i}));
end

d.dot_z_eq = 4*(d.lz_eq - d.lz_eq{-1});

%% Trend and Gap for Output - Band-pass filter
d.lgdp_gap = bpass(d.lgdp,inf,[6,32],'detrend',false);
d.lgdp_eq = hpf((d.lgdp-d.lgdp_gap),inf,'lambda',5);
d.dot_gdp_eq = 4*(d.lgdp_eq - d.lgdp_eq{-1});

%% Foreign Output gap - Band-pass filter
d.lx_gdp_gap = bpass(d.lx_gdp,inf,[6,32],'detrend',false);
d.lx_gdp_eq = hpf((d.lx_gdp-d.lx_gdp_gap),inf,'lambda',5);

%% Real monetary conditions and real marginal cost 
d.mci = p.a4*d.rr_gap + (1-p.a4)*(-d.lz_gap);
d.rmc = p.b3*d.lgdp_gap + (1-p.b3)*d.lz_gap;

%% Policy neutral rate
d.rn_neutral = d.rr_eq + d.dot4_cpi;

%% Inflation target (history) - not applied for the Czech Republic (target is known)
% d.target = hpf(d.dot_cpi);

%% If you want use a different number for the end value (there is 10 as a proxy) change the first lines 
% prior_cpi = tseries(get(d.dot_cpi,'end'),10);
% d.target = hpf(d.dot_cpi,inf,'level',prior_cpi);

%% Compute the exchange rate target over the history
% Exchange rate target is automatically calculated as to equal observed
% exchange rate at the end of the sample
prior_ls_tar = tseries(get(d.ls,'last'),d.ls(end));
d.ls_tar = hpf(d.ls,inf,'lambda',1600,'level',prior_ls_tar);
d.dot_s_tar = 4*(d.ls_tar - d.ls_tar{-1});

%% Risk premium
d.prem = d.dot_z_eq - d.rr_eq + d.x_rr_eq;
d.shock_prem = tseries(get(d.ls,'range'),0);

%% Credit premium
d.cr_prem = tseries(get(d.rr_gap,'range'),0);

%% Expert change in the database--output gap
% d.lgdp_gap(qq(2012,4):qq(2013,2)) = [-2 1 2];

%% Expert change in the database--FOREIGN output gap
% Make sure that the last 5-6 observations by the HP filter correspond  
% to WEO, GPM etc. "Bad" values will compromise the kalman filter results.
% Override if necessary using GPM, WEO, and so on:

% d.lx_gdp_gap(qq(2011,1):qq(2014,1)) = [-1 -0.9 -1.3 -1.6 -2 -2.1 -2.3 -2.7 -3 -3.2 -3.4 -3.6 -3.5];

%% Sets cumulative output gap zero at the end of the observed sample
d.cum_gap = tseries(get(d.lgdp,'first2last'),0);

%% Save the database
% Database is saved in file 'history.csv'
dbsave(d,'history.csv');

%% Report - Stylized Facts
% Specify country
country = 'The Czech Republic - Stylized Facts';
exchange = 'CZK/EUR';

% Report
x = report.new(country);

% Figures
rng = get(d.dot4_cpi,'first2last');

sty = struct();
sty.line.linewidth = 1;
sty.line.linestyle = {'-';'--'};
sty.line.color = {'k';'k'};
sty.axes.box = 'on';

x.figure('Nominal Variables','subplot',[3,3],'style',sty,'range',rng,...
  'dateformat','YY:P','figuretrim',[40,0,40,40]);

x.graph('Inflation','legend',true,'legendLocation','bottom');
x.series('',[d.dot_cpi d.dot4_cpi],'legendEntry=',{'q-o-q','y-o-y'});

x.graph('Core Inflation','legend',false);
x.series('',[d.dot_cpi_x d.dot4_cpi_x]);

x.graph('Food Inflation','legend',false);
x.series('',[d.dot_cpi_food d.dot4_cpi_food]);

x.graph('Oil Inflation','legend',false);
x.series('',[d.dot_cpi_oil d.dot4_cpi_oil]);

x.graph('Foreign Inflation','legend',false);
x.series('',[d.dot_x_cpi d.dot4_x_cpi]);

x.graph(exchange,'legend',false);
x.series('',[d.s]);

x.graph('Nominal Exchange Rate','legend',false);
x.series('',[d.dot_s d.dot4_s]);

x.graph('Nominal Interest Rate','legend',false);
x.series('',[d.rn]);

x.graph('Foreign Nominal Interest Rate','legend',false);
x.series('',[d.x_rn]);

x.pagebreak();

x.figure('Real Variables','subplot',[2,3],'style',sty,'range',rng,...
  'dateformat','YY:P','figuretrim',[40,0,40,40]);

sty_tmp = sty;
sty_tmp.legend.location = 'southOutside';
sty_tmp.legend.orientation = 'horizontal';
x.graph('GDP Growth','legend',true,'style',sty_tmp);
x.series('',[d.dot_gdp d.dot4_gdp],'legendEntry=',{'q-o-q','y-o-y'});

x.graph('GDP','legend',true,'legendLocation','bottom');
x.series('',[d.lgdp d.lgdp_eq],'legendEntry=',{'level','trend'});

x.graph('Real Interest Rate','legend',false);
x.series('',[d.rr d.rr_eq],'legendEntry=',{'level','trend'});

x.graph('Real Exchange Rate','legend',false);
x.series('',[d.lz d.lz_eq],'legendEntry=',{'level','trend'});

x.graph('Foreign GDP','legend',false);
x.series('',[d.lx_gdp d.lx_gdp_eq],'legendEntry=',{'level','trend'});

x.graph('Foreign Real Interest Rate','legend',false);
x.series('',[d.x_rr d.x_rr_eq],'legendEntry=',{'level','trend'});

x.pagebreak();

x.figure('Gaps','subplot',[3,2],'style',sty,'range',rng,'dateformat','YY:P');

x.graph('GDP Gap','legend',false);
x.series('',[d.lgdp_gap]);

x.graph('Monetary Conditions','legend',false);
x.series('',[d.mci]);

x.graph('Real Interest Rate Gap','legend',false);
x.series('',[d.rr_gap]);

x.graph('Real Exchange Rate Gap','legend',false);
x.series('',[d.lz_gap]);

x.graph('Relative Food Price (Gap)','legend',false);
x.series('',[d.lz_food_gap]);

x.graph('Foreign GDP Gap','legend',false);
x.series('',[d.lx_gdp_gap]);
  
x.publish('Stylized_facts','display',false);
disp('Done!!!');
